# -*- coding: utf-8 -*-
import traceback, os, datetime
from MongoDbLog import MongoDbLog
import mechanize, urllib, urllib2
from lxml import etree
import cStringIO as StringIO

stringify = etree.XPath("String()")
url = "http://m11.nhaccuatui.com/api/mobile.ashx"
def getXMLTree(url, data={}, headers={}, isXML=False, outputHTML=False, cookie=None, debugLevel=0, userAgent='', root_url='', timeout=300):
    print 'DEBUG: start getXMLTree(url={0}, data={1})'.format(url, data)
    tree = None
    error = False
    try:
        debugHandler = mechanize.HTTPHandler()
        debugHandler.set_http_debuglevel(debugLevel)
        if cookie == None: cookie = mechanize.LWPCookieJar()
        opener = mechanize.build_opener(debugHandler, mechanize.HTTPCookieProcessor(cookie), mechanize.HTTPRedirectHandler)
        if userAgent == '':
            aH = [("User-Agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1")]
        else:
            aH = [("User-Agent", userAgent)]
        for i, v in headers.items(): aH.append((i, v))
        opener.addheaders = aH
        mechanize.install_opener(opener)
        request = mechanize.Request(url, urllib.urlencode(data)) if len(data) > 0 else mechanize.Request(url)
        response = mechanize.urlopen(request, timeout=timeout)
        if root_url != '':
            if response.geturl() == root_url: raise Exception("server redirected to {0}".format(root_url))
        html = response.read()
        content_type = response.info().getheader('Content-Encoding', '')
        if content_type == 'gzip':
            gzipper = gzip.GzipFile(fileobj=StringIO.StringIO(html))
            html = gzipper.read()
        if outputHTML==True: print html
        parser = etree.XMLParser(encoding='utf-8') if isXML==True else etree.HTMLParser(encoding='utf-8')
        tree = etree.parse(StringIO.StringIO(html), parser)
    except mechanize.HTTPError, e:
        error = True; logger.error(e)
    except mechanize.URLError, e:
        error = True; logger.error(e.reason)
    finally:
        if not error:
            print 'DEBUG: finished getXMLTree(url={0}, data={1})'.format(url, data)
        else:
            print 'ERROR: failed getXMLTree(url={0}, data={1})'.format(url, data)
    return tree
    
def getTree(url, data= {}, outputHTML=False):
  try:
    #cookies = mechanize.CookieJar()
    #opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
    #mechanize.install_opener(opener)
    request = mechanize.Request(url, urllib.urlencode(data))
    response = mechanize.urlopen(request)
    html = response.read()
    if outputHTML: print html
    tree = etree.parse(StringIO.StringIO(html), etree.XMLParser(encoding='utf-8'))
    return tree
  except:
    traceback.print_exc()
    
#post = {'secretkey': 'nct@mobile!team', 'action': 'topsong', 'perpage': '20', 'curpage': '1', 'deviceinfo': {"DeviceID":"000000000000000","OsName":"Android","OsVersion":"2.3.3","AppName":"NhacCuaTui","AppVersion":"3.0.1","UserInfo":"","LocationInfo":""}}
#post = {'secretkey': 'nct@mobile!team', 'action': 'getListPlaylistByGenre', 'genreId': '5118', 'perpage': '10', 'curpage': '2', 'deviceinfo': {"DeviceID":"000000000000000","OsName":"Android","OsVersion":"2.3.3","AppName":"NhacCuaTui","AppVersion":"3.0.1","UserInfo":"","LocationInfo":""}}
post = {'secretkey': 'nct@mobile!team', 'action': 'getPlaylistInfo', 'listkey': '6MFby0IqQ16d', 'deviceinfo': {"DeviceID":"000000000000000","OsName":"Android","OsVersion":"2.3.3","AppName":"NhacCuaTui","AppVersion":"3.0.1","UserInfo":"","LocationInfo":""}}
#tree = getXMLTree(url, post, isXML=True, outputHTML=False, userAgent="NCTMusic/1.0 CFNetwork/485.12.7")    
tree = getTree(url, post)
listNode = tree.xpath('//item')
f = open('C:/test.txt', 'w')
for node in listNode:
  titleNode = node.xpath('.//name')
  urlNode = node.xpath('.//url')
  if len(titleNode) > 0:
    #print etree.tostring(titleNode[0])
    name = titleNode[0].text
    if type(name).__name__ == 'unicode': name = name.encode('utf-8')
    print name, urlNode[0].text
    f.write(urlNode[0].text)
    print '--------------'
f.close()

'''
class NCT():
    
    def __init__(self):
        self.userAgent = 'NCTMusic/1.0 CFNetwork/485.12.7 Darwin/10.4.0'
        self.url = 'http://m11.nhaccuatui.com/RestfulAPI.ashx'
        self.post = {'secretkey': 'nct@mobile!team'}
    
    def getListCategories(self):
        post = self.post
        post['action'] = 'genres'
        tree = commonlib.getXMLTree(url, post, isXML=True, useragent=self.userAgent, outputHTML=True)
    
if __name__ == '__main__':
    
    nct = NCT()
    nct.getListCategories()
    
    os._exit(1)
'''
    
'''
---- lay danh muc


POST http://m11.nhaccuatui.com/RestfulAPI.ashx HTTP/1.1
Host: m11.nhaccuatui.com
User-Agent: NCTMusic/1.0 CFNetwork/485.12.7 Darwin/10.4.0
Content-Length: 39
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: keep-alive
Connection: keep-alive

secretkey=nct@mobile!team&action=genres


---- list song by danh muc



secretkey=nct@mobile!team&action=getListSongByGenre&genreid=5015&currentpage=1&perpage=10


---- top new song



secretkey=nct@mobile!team&action=topNewSong&numbersongs=20


---- top hot song


secretkey=nct@mobile!team&action=topHotSong&numbersongs=20

---- playlist chonloc



secretkey=nct@mobile!team&action=searchPlaylist&keyword=&currentpage=1&perpage=10&searchtype=chonloc


---- search bai hat


secretkey=nct@mobile!team&action=search&keyword=anh&currentpage=1&perpage=30&searchtype=chonloc

---- search playlist

secretkey=nct@mobile!team&action=searchPlaylist&keyword=anh&currentpage=1&perpage=30&searchtype=chonloc
'''

